const axios = require('axios');
const { config } = require('../config');

class BarkChannel {
  constructor(customConfig) {
    this.cfg = customConfig || config.bark;
    if (!this.cfg.baseUrl) {
      throw new Error('Bark baseUrl is required');
    }
  }

  async send(message) {
    const { title, body, group, sound, icon, archive } = this._buildPayloadDefaults(message);
    const deviceKeys = (message.deviceKeys && message.deviceKeys.length ? message.deviceKeys : this.cfg.deviceKeys) || [];
    if (deviceKeys.length === 0) {
      throw new Error('No Bark device keys configured');
    }

    const results = [];
    for (const deviceKey of deviceKeys) {
      const url = this._resolvePushUrl();
      const payload = {
        device_key: deviceKey,
        title,
        body,
        group,
        sound,
        icon,
        isArchive: archive
      };
      try {
        const res = await axios.post(url, payload, { timeout: 10000 });
        results.push({ deviceKey, ok: true, data: res.data });
      } catch (err) {
        results.push({ deviceKey, ok: false, error: err.message });
      }
    }
    const hasFailure = results.some(r => !r.ok);
    if (hasFailure) {
      const error = new Error('Some Bark notifications failed');
      error.results = results;
      throw error;
    }
    return results;
  }

  _resolvePushUrl() {
    // Prefer official /push endpoint
    const base = this.cfg.baseUrl.replace(/\/$/, '');
    return `${base}/push`;
  }

  _buildPayloadDefaults(message) {
    return {
      title: message.title || '',
      body: message.body || '',
      group: message.group !== undefined ? message.group : this.cfg.group,
      sound: message.sound !== undefined ? message.sound : this.cfg.sound,
      icon: message.icon !== undefined ? message.icon : this.cfg.icon,
      archive: message.archive !== undefined ? message.archive : this.cfg.archive
    };
  }
}

module.exports = { BarkChannel };


